/**
 * Created by Administrator on 2017/8/19 0019.
 */
var host = window.location.origin;
isWeiXin();
var queryString = function () {
    // This function is anonymous, is executed immediately and
    // the return value is assigned to QueryString!
    //如何利用 JS 脚本捕获页面 GET 方式请求的参数？其实直接使用 window.location.search 获得，然后通过 split 方法结合循环遍历自由组织数据格式。
    var query_string = {};
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        // If first entry with this name
        if (typeof query_string[pair[0]] === "undefined") {
            query_string[pair[0]] = pair[1];
            // If second entry with this name
        } else if (typeof query_string[pair[0]] === "string") {
            var arr = [query_string[pair[0]], pair[1]];
            query_string[pair[0]] = arr;
            // If third or later entry with this name
        } else {
            query_string[pair[0]].push(pair[1]);
        }
    }
    return query_string;
};

function isWeiXin(){
    var ua = window.navigator.userAgent.toLowerCase();
    if(ua.match(/MicroMessenger/i) != 'micromessenger'){
        //location.href =host+'/view/fish.html';
    }
}

function dateFormate(d){
    d = new Date(d);
    return d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
}

//写cookies
function setCookie(name, value) {

    var exp = new Date();
    exp.setTime(exp.getTime() + 24 * 60 * 60 * 1000);		//1天
    document.cookie = name + "=" + encodeURI(value) + ";expires=" + exp.toGMTString();
    //document.cookie = name + "=" + encodeURI(value);
}

//读取cookies
function getCookie(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg)) {
        if (arr[2]) {
            return decodeURI(arr[2]);
        } else {
            return null;
        }
    }
    else {
        return null;
    }

}

//删除cookies
function delCookie(name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(name);
    if (cval != null)
        document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
}

function getDisWxCode() {
    var params = queryString();
    //alert(window.location.href);
    //alert(JSON.stringify(params));
    if (params.referee) {
        setCookie('disRef', params.referee);
    }
    if (params.regChannel) {
        setCookie('disReg',params.regChannel);
    }
    var openid = getCookie("disOpenid");

    if (openid == null) {               //没有唯一标识
        var access_code = params.code;
        //console.log('1. access_code: '+access_code);
        if (!access_code) {      //获取微信code
            var redUrl = encodeURIComponent('http://weblogin.178dn.net/view/disWebAuth.html?referee='+getCookie('disRef')+'&regChannel='+getCookie('disReg')+'&=');
            var loc = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd44830a7fce3040d&redirect_uri='+redUrl+'+&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
            location.href = loc;
        } else {

            $.ajax({
                url: host + "/disWxOpenid",   //请求的url地址
                dataType:"json",   //返回格式为json
                async:true,//请求是否异步，默认为异步，这也是ajax重要特性
                cache:false,
                headers: {"content-type": "application/json","Cache-Control":"no-cache, must-revalidate","access_code": access_code,"referee": getCookie('disRef'),"regchannel":getCookie('disReg')},
                type:"GET",   //请求方式
                success:function(data){
                    if (data.code) {
                        //alert('wxOpenid code1');
                        var redUrl = encodeURIComponent('http://weblogin.178dn.net/view/disWebAuth.html?');
                        var loc = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd44830a7fce3040d&redirect_uri='+redUrl+'+&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
                        location.href = loc;
                    } else {
                        //alert('2.!!sid'+data.user.sid);
                        setCookie('disOpenid', data.openid);
                        setCookie('disUid', data.user.uid);
                        setCookie('disCoin', data.user.coin);
                        setCookie('disPoin', data.user.poin);
                        setCookie('disVip', data.user.vip);
                        location.href = 'http://disa.178dn.net/distribution/view/me.html?disOpenid='+data.openid+'&disUid='+data.user.uid+'&disCoin='+data.user.coin+'&disPoin='+data.user.poin+'&disVip='+data.user.vip;
                    }
                },
                error:function(){
                    //alert('wxOpenid error!!');
                    var redUrl = encodeURIComponent('http://weblogin.178dn.net/view/disWebAuth.html?');
                    var loc = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd44830a7fce3040d&redirect_uri='+redUrl+'+&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
                    location.href = loc;
                }
            });
        }
    } else {             //有openid,获取个人信息
        //alert('1.1.openid'+openid);
        $.ajax({
            url: host + "/disUserInfo",
            type: "GET",
            dataType: 'json',
            async:true,//请求是否异步，默认为异步，这也是ajax重要特性
            headers: {"content-type": "application/json","disopenid":openid},
            success :function (data) {
                if (data.code) {
                    var redUrl = encodeURIComponent('http://weblogin.178dn.net/view/minWheel.html?');
                    var loc = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd44830a7fce3040d&redirect_uri='+redUrl+'+&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
                    location.href = loc;
                } else {
                    //alert('3.~~data.user.sid'+data.user.sid);
                    setCookie('disUid', data.user.uid);
                    setCookie('disCoin', data.user.coin);
                    setCookie('disPoin', data.user.poin);
                    setCookie('disVip', data.user.vip);
                    location.href = 'http://disa.178dn.net/distribution/view/me.html?disOpenid='+data.openid+'&disUid='+data.user.uid+'&disCoin='+data.user.coin+'&disPoin='+data.user.poin+'&disVip='+data.user.vip;
                }
            },
            error:function () {
                var redUrl = encodeURIComponent('http://weblogin.178dn.net/view/minWheel.html?');
                var loc = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd44830a7fce3040d&redirect_uri='+redUrl+'+&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
                location.href = loc;
            }
        });
    }
};

function onBridgeReady(prepay_id, pay_sign, nonce_str, time_stamp) {
    var flag = false;
    WeixinJSBridge.invoke(
        'getBrandWCPayRequest', {
            "appId": "wxd44830a7fce3040d", //公众号名称，由商户传入
            "timeStamp": time_stamp,  //时间戳，自1970年以来的秒数
            "nonceStr": nonce_str, //随机串
            "package": "prepay_id=" + prepay_id,
            "signType": "MD5",  //微信签名方式:
            "paySign": pay_sign //微信签名
        },
        function (res) {
            if (res.err_msg == "get_brand_wcpay_request:ok") {// 使用以上方式判断前端返回,微信团队郑重提示:res.err_msg将在用户支付成功后返回 ok，但并不保证它绝对可靠。
                layer.open({
                    content: '成功解锁会员特权,块分享给自己的好友吧!'
                    ,skin: 'msg'
                    ,time: 2 //2秒后自动关闭
                });
                flag = true;
            } else {
                layer.open({
                    content: '8一8,才能发发发呦'
                    ,skin: 'msg'
                    ,time: 1.5 //2秒后自动关闭
                });
            }

            return flag;
        }
    );
}
